package com.redis.demo.core.dao.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.redis.demo.core.dao.IBaseDao;

import redis.clients.jedis.Jedis;

public class BaseDaoByRedis<T> implements IBaseDao {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	private Class<T> entityClass;
	private String simpleName;

	@Autowired
	protected Jedis jedis = null;

	public BaseDaoByRedis(Class<T> entityClass) {
		this.entityClass = entityClass;
		this.simpleName = this.entityClass.getSimpleName();
	}

	/**
	 * 默认使用 uuid 方式 产生主键
	 * 
	 * @return
	 */
	protected String uuid() {
		return UUID.randomUUID().toString();
	}

	protected byte[] key(String id) {
		try {
			return (simpleName() + id).getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	protected String simpleName() {
		return this.simpleName;
	}

	/**
	 * 序列化
	 * 
	 * @param o
	 * @return
	 * @throws IOException
	 */
	public byte[] serial(T o) {

		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(o);
			byte[] bytes = bos.toByteArray();
			bos.close();
			oos.close();

			return bytes;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 恢复对象
	 * 
	 * @param bytes
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("unchecked")
	public T unSerial(byte[] bytes) {
		try {
			if (bytes == null) {
				return null;
			}
			ObjectInputStream ois = new ObjectInputStream(
					new ByteArrayInputStream(bytes));
			T t = (T) ois.readObject();
			ois.close();
			return t;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
